<!-- 耗量明细 -->
<template>
  <div class="flex-center table-top">
    <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
      <px-form-item label="设备编号" prop="eqpNo">
        <px-input v-model.trim="queryParams.eqpNo" style="width: 260px" placeholder="请输入设备编号" clearable />
      </px-form-item>
      <px-form-item label="气体种类" prop="type">
        <px-select v-model="queryParams.type" style="width: 260px" placeholder="请选择气体种类" clearable filterable>
          <px-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="单位" prop="unit">
        <px-select v-model="queryParams.unit" style="width: 260px" placeholder="请选择单位" clearable filterable>
          <px-option v-for="item in unitList" :key="item.id" :label="item.name" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="日期" prop="date">
        <px-date-picker v-model="queryParams.date" type="date" style="width: 260px" placeholder="请选择日期" value-format="YYYY-MM-DD" />
      </px-form-item>
      <div class="search-form-btn">
        <px-button type="primary" @click="handleQuery">查询</px-button>
        <px-button @click="resetQuery">重置</px-button>
        <px-button v-has="`GAS_CONSUMPTION_SPECIALGAS_DETAIL_EXPORT_BTN`" @click="handleExport">导出</px-button>
      </div>
    </px-form>
  </div>
  <div ref="tableBoxRef" v-loading="tableLoading" class="table-content">
    <px-table
      ref="tableRef"
      :data="tableData"
      size="small"
      border
      class="common-table"
      :cell-style="tableCellStyle"
      :scrollbar-always-on="true"
      :height="scrollbarHeight"
    >
      <px-table-column type="index" label="序号" fixed width="55" align="center" />
      <px-table-column prop="itemKey" label="设备编号" fixed min-width="90" show-overflow-tooltip />
      <px-table-column prop="gasName" label="气体种类" fixed min-width="70" show-overflow-tooltip />
      <px-table-column prop="unit" label="单位" fixed min-width="50" show-overflow-tooltip />
      <px-table-column
        v-for="(item, index) in dateList"
        :key="item.date"
        prop="date"
        :label="`${item.date}(${item.week})`"
        min-width="135"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div
            v-if="
              scope.row.statDetailDTOList[index]?.statValue !== null &&
              scope.row.statDetailDTOList[index]?.oos &&
              scope.row.statDetailDTOList[index]?.reason !== null &&
              scope.row.statDetailDTOList[index]?.reason !== ''
            "
          >
            <px-popover
              placement="top-start"
              title="提示"
              :width="200"
              trigger="hover"
              :content="`${scope.row.itemKey} 机台用量超标。原因：${scope.row.statDetailDTOList[index].reason}`"
            >
              <template #reference>
                <div class="date-cell">
                  <span :style="getCellStyle(scope.row.statDetailDTOList[index])">
                    {{ scope.row.statDetailDTOList[index].statValue }}
                  </span>
                </div>
              </template>
            </px-popover>
          </div>
          <div
            v-if="
              scope.row.statDetailDTOList[index]?.statValue !== null &&
              scope.row.statDetailDTOList[index]?.oos &&
              (scope.row.statDetailDTOList[index]?.reason === null || scope.row.statDetailDTOList[index]?.reason === '')
            "
            class="date-cell"
            @click="setReason(scope.row, index)"
          >
            <span :style="getCellStyle(scope.row.statDetailDTOList[index])">
              {{ scope.row.statDetailDTOList[index]?.statValue }}
              <px-tooltip content="请发邮件咨询耗量异常原因，并回填结果">
                <px-icon size="16">
                  <WarnTriangleFilled />
                </px-icon>
              </px-tooltip>
            </span>
          </div>
          <div v-if="!scope.row.statDetailDTOList[index]?.oos" class="date-cell">
            <span>
              {{ scope.row.statDetailDTOList[index]?.statValue }}
            </span>
          </div>
        </template>
      </px-table-column>
      <px-table-column prop="showLslValue" label="SPEC L" min-width="60" fixed="right" show-overflow-tooltip />
      <px-table-column prop="showTargetValue" label="Target" min-width="60" fixed="right" show-overflow-tooltip />
      <px-table-column prop="showUslValue" label="SPEC U" min-width="60" fixed="right" show-overflow-tooltip />
      <px-table-column label="操作" min-width="60" fixed="right" align="center">
        <template #default="scope">
          <px-tooltip content="编辑" placement="top">
            <px-button v-has="`GAS_CONSUMPTION_SPECIALGAS_DETAIL_EDIT_BTN`" link icon="EditPen" type="primary" @click="handleEdit(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>
  </div>
  <px-dialog v-model="editDialogVisible" title="编辑" width="800">
    <div class="dialog-wrap">
      <px-form ref="editFormRef" :model="editFormParams" class="left-form">
        <div class="title">固定值</div>
        <px-form-item label="SPEC L" prop="lslValue" label-width="80">
          <px-input v-model.trim="editFormParams.lslValue" placeholder="请输入" clearable />
        </px-form-item>
        <px-form-item label="Target" prop="targetValue" label-width="80">
          <px-input v-model.trim="editFormParams.targetValue" placeholder="请输入" clearable />
        </px-form-item>
        <px-form-item label="SPEC U" prop="uslValue" label-width="80">
          <px-input v-model.trim="editFormParams.uslValue" placeholder="请输入" clearable />
        </px-form-item>
      </px-form>
      <div class="mid-wrap" />
      <px-form ref="editFormRef2" :model="editFormParams" class="right-form">
        <div class="title">计算公式</div>
        <px-form-item label="SPEC L = " prop="percentageLslValue" label-width="80">
          <div class="text">Target*</div>
          <px-input v-model.trim="editFormParams.percentageLslValue" placeholder="请输入" clearable style="width: 80px" />
          <div class="text">%</div>
        </px-form-item>
        <px-form-item label="Target = " prop="percentageTargetValue" label-width="80">
          <px-input v-model.trim="editFormParams.percentageTargetValue" placeholder="请输入" clearable style="width: 80px" />
          <div class="text">日均值</div>
        </px-form-item>
        <px-form-item label="SPEC U = " prop="percentageUslValue" label-width="80">
          <div class="text">Target*</div>
          <px-input v-model.trim="editFormParams.percentageUslValue" placeholder="请输入" clearable style="width: 80px" />
          <div class="text">%</div>
        </px-form-item>
      </px-form>
    </div>
    <div class="text">注：优先按照固定值运行，无需固定值请空置</div>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelEdit">取消</px-button>
        <px-button type="primary" @click="saveEdit">确定</px-button>
      </span>
    </template>
  </px-dialog>

  <px-dialog v-model="reasonDialogVisible" title="编辑" width="400">
    <px-form :model="reasonFormParams">
      <px-form-item label="原因" prop="reason">
        <px-input v-model.trim="reasonFormParams.reason" placeholder="请输入" clearable type="textarea" />
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelSetReason">取消</px-button>
        <px-button type="primary" @click="submitReason">确定</px-button>
      </span>
    </template>
  </px-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, onUnmounted, nextTick, getCurrentInstance } from "vue";
import { getBeforeDate, getWeek, getYesterday } from "../../utils.js";
import { getDetailListAPI, editDetailListAPI, setOOSReasonAPI } from "@/api/consumption/specialGas";
import { queryDictData } from "@/api/common";
import { queryEquipSystem } from "@/api/equip/archive";
import { PxMessage } from "px-ui";
import { useExportHook } from "../../hook.js";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";

defineOptions({
  name: "GAS_CONSUMPTION_SPECIALGAS_DETAILLIST"
});

const formRef = ref(null);
const tableRef = ref(null);
const editFormRef = ref(null);
const editFormRef2 = ref(null);
const { proxy } = getCurrentInstance();

const gap = 40;
const defaultHeight = 606;
const scrollbarHeight = ref<number>(defaultHeight);
const tableBoxRef = ref<HTMLElement | null>(null);

const state = reactive({
  queryParams: {
    eqpNo: "",
    type: "",
    unit: "",
    date: ""
  },
  editFormParams: {
    lslValue: "",
    targetValue: "",
    uslValue: "",
    percentageLslValue: "",
    percentageTargetValue: "",
    percentageUslValue: ""
  },
  reasonFormParams: {
    reason: ""
  },
  typeList: [],
  unitList: [],
  tableData: [],
  dateList: [],
  tableLoading: false,
  editDialogVisible: false,
  reasonDialogVisible: false,
  rowData: {},
  dateIndex: 0
});
const {
  queryParams,
  editFormParams,
  reasonFormParams,
  typeList,
  unitList,
  tableData,
  dateList,
  tableLoading,
  editDialogVisible,
  reasonDialogVisible,
  rowData,
  dateIndex
} = toRefs(state);

onMounted(async () => {
  getUnitList();
  getGasTypeList();
  handleQuery();
  await useUpdateDomHeight(scrollbarHeight, tableBoxRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());

const params = {
  itemKey: state.queryParams?.eqpNo,
  gasSystemCode: state.queryParam?.type.toString(),
  unit: state.queryParam?.unit,
  searchDate: state.queryParam?.date
};
const { handleExport } = useExportHook(proxy, "SPECIALTY_GAS", params);

// 获取单位下拉框
const getUnitList = async () => {
  state.unitList = await queryDictData({ typeCode: "SPECIALTY_GAS_UNIT" });
};

// 获取气体种类下拉框
const getGasTypeList = async () => {
  const res = await queryEquipSystem({ className: "GAS" });
  // facCode   一期  FAC_83abf9   二期  FAC_93abf6
  const facCode = localStorage.getItem("facCode");
  const systemCode = facCode === "FAC_83abf9" ? "SCA6CC96" : facCode === "FAC_93abf6" ? "SCC3F1B9" : "";
  const t = res.find(item => item.code === systemCode);
  if (!t?.children?.length) return;
  state.typeList = t.children.map(item => {
    let { name, code } = item;
    const reg = new RegExp("供应系统", "g");
    name = name.replace(reg, "");
    return { label: name, value: code };
  });
  state.typeList = state.typeList.filter(item => item.label !== "辅助系统");
  state.typeList = state.typeList.filter(item => item.label !== "电力系统");
  state.typeList = state.typeList.filter(item => item.label !== "Gas-Hookup");
};

// 查询
const handleQuery = async () => {
  try {
    state.tableLoading = true;
    const { eqpNo, type, unit, date } = state.queryParams;
    const params = {
      itemKey: eqpNo,
      gasSystemCode: type.toString(),
      unit: unit,
      searchDate: date
    };
    state.tableData = await getDetailListAPI(params);
    let arr = [];
    let d = null;
    if (date === "" || date === null) {
      d = getYesterday();
    } else {
      d = date;
    }
    // 特气这边默认取的是昨天往前7天，包含昨天，因为今天的数据要明天5点才能出来
    for (let i = 6; i > -1; i--) {
      arr.push({
        date: getBeforeDate(i, d),
        week: getWeek(getBeforeDate(i, d))
      });
    }
    state.dateList = arr;
    // 调试
    // state.dateList.splice(0, 7);
    nextTick(() => {
      tableRef.value.setScrollLeft(2000);
    });
  } catch (err) {
    console.log(err);
  } finally {
    state.tableLoading = false;
  }
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

const getCellStyle = item => {
  let style = {};
  if (item.oos) {
    style.color = "#fff";
  }
  return style;
};

// oos的数据单元格背景色为红色
const tableCellStyle = ({ row, column, rowIndex, columnIndex }) => {
  let style = {};
  row.statDetailDTOList.map((v, i) => {
    if (column.property === "date" && v.oos && columnIndex - 4 === i) {
      style.background = "#EF4444";
      style.color = "#fff";
    }
    return style;
  });
  return style;
};

// 编辑
const handleEdit = row => {
  state.editDialogVisible = true;
  state.rowData = row;
  state.editFormParams = {
    lslValue: row.lslValue,
    targetValue: row.targetValue,
    uslValue: row.uslValue,
    percentageLslValue: row.percentageLslValue,
    percentageTargetValue: row.percentageTargetValue,
    percentageUslValue: row.percentageUslValue
  };
};

// 取消编辑
const cancelEdit = () => {
  editFormRef.value.resetFields();
  state.editDialogVisible = false;
};

// 保存编辑
const saveEdit = async () => {
  const { lslValue, targetValue, uslValue, percentageLslValue, percentageTargetValue, percentageUslValue } = state.editFormParams;
  if (parseFloat(lslValue) > parseFloat(uslValue)) {
    PxMessage.error("SPEC L 要小于等于 SPEC U");
    return;
  }
  if (parseFloat(percentageLslValue) > parseFloat(percentageUslValue)) {
    PxMessage.error("SPEC L 要小于等于 SPEC U");
    return;
  }
  const params = {
    itemKey: state.rowData.itemKey,
    lslValue: lslValue,
    targetValue: targetValue,
    uslValue: uslValue,
    percentageLslValue: percentageLslValue,
    percentageTargetValue: percentageTargetValue,
    percentageUslValue: percentageUslValue
  };
  await editDetailListAPI(params);
  cancelEdit();
  handleQuery();
  PxMessage.success("修改成功");
};

const setReason = (row, index) => {
  state.rowData = row;
  state.dateIndex = index;
  state.reasonDialogVisible = true;
};

const cancelSetReason = () => {
  state.reasonDialogVisible = false;
};

const submitReason = async () => {
  const params = {
    itemKey: state.rowData.itemKey,
    statDate: state.rowData.statDetailDTOList[state.dateIndex].statDate,
    reason: state.reasonFormParams.reason
  };
  await setOOSReasonAPI(params);
  PxMessage.success("操作成功");
  state.reasonDialogVisible = false;
  handleQuery();
};
</script>

<style lang="scss" scoped>
@import url("@/views/gas/consumption/scss/common.scss");

.date-cell {
  width: 100%;
  height: 100%;
}
</style>
